package cn.itcast.controller.cargo;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.cargo.ContractExample;
import cn.itcast.domain.cargo.Export;
import cn.itcast.domain.cargo.ExportExample;
import cn.itcast.domain.cargo.ExportProduct;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.ExportProductService;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.utils.BeanMapUtils;
import cn.itcast.utils.DownloadUtil;
import cn.itcast.vo.ExportProductVo;
import cn.itcast.vo.ExportResult;
import cn.itcast.vo.ExportVo;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.commons.lang.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.*;

@Controller
@RequestMapping("/cargo/export")
public class ExportController extends BaseController {

    @Reference
    private ContractService contractService;
    @Reference
    private ExportService exportService;
    @Reference
    private ExportProductService exportProductService;

    @RequestMapping(value = "/contractList",name = "分页展示已提交的购销合同分页列表数据")
    public String contractList(@RequestParam(value ="page",defaultValue = "1") Integer pageNumber, @RequestParam(value ="size",defaultValue = "10")  Integer pageSize){
//        构建根据企业id查询条件
        ContractExample example = new ContractExample();
        example.setOrderByClause("create_time desc");
        ContractExample.Criteria criteria = example.createCriteria().andCompanyIdEqualTo(getCompanyId());//   select * from co_contract where company_id=??
       criteria.andStateEqualTo(1);
        PageInfo pageInfo = contractService.findAll(example, pageNumber, pageSize);

        request.setAttribute("page",pageInfo);

        return "/cargo/export/export-contractList";

}

    @RequestMapping(value = "/list",name = "分页展示报运单列表数据")
    public String list(@RequestParam(value ="page",defaultValue = "1") Integer pageNumber, @RequestParam(value ="size",defaultValue = "10")  Integer pageSize){
//        构建根据企业id查询条件
        ExportExample example = new ExportExample();
        example.setOrderByClause("create_time desc");
        ExportExample.Criteria criteria = example.createCriteria().andCompanyIdEqualTo(getCompanyId());//   select * from co_contract where company_id=??
        PageInfo pageInfo = exportService.findAll(example, pageNumber, pageSize);

        request.setAttribute("page",pageInfo);

        return "/cargo/export/export-list";

    }


    @RequestMapping(value = "/toExport",name = "进入到新增报运单页面")
    public String toExport(String id){ // "12121,13223" // String id  String[] id     @RequestParan("id") List<String> id
        request.setAttribute("id",id);
        return "/cargo/export/export-toExport";
    }

    @RequestMapping(value = "/toUpdate",name = "进入到修改报运单页面")
    public String toUpdate(String id){
//        当前报运单对象  货物数据
        Export export = exportService.findById(id);
        request.setAttribute("export",export);
//        select * from co_export_product where export_id= id
       List<ExportProduct> exportProductList =  exportProductService.findByExportId(id);
        request.setAttribute("eps",exportProductList);

        return "/cargo/export/export-update";
    }

    @RequestMapping(value = "/edit",name = "保存报运单")
    public String edit(Export export){
        if(StringUtils.isEmpty(export.getId())){
            export.setId(UUID.randomUUID().toString());
            export.setCreateBy(getUser().getId());
            export.setCreateDept(getUser().getDeptId());
            export.setCreateTime(new Date());
            export.setCompanyId(getCompanyId());
            export.setCompanyName(getCompanyName());
            export.setState(0);
            exportService.save(export);
        }else{
            exportService.update(export);
        }
        return "redirect:/cargo/export/list.do";
    }



    @RequestMapping(value = "/exportE",name = "海关电子报运")
    public String exportE(String id){
        Export export = exportService.findById(id);
        ExportVo exportVo = new ExportVo();
        BeanUtils.copyProperties(export,exportVo);
        exportVo.setExportId(id);
//        需要手动设置exportId来自于Export的id，List<ExportProductVo>
        List<ExportProduct> exportProductList = exportProductService.findByExportId(id);
        for (ExportProduct exportProduct : exportProductList) {
            ExportProductVo exportProductVo = new ExportProductVo();
            BeanUtils.copyProperties(exportProduct,exportProductVo);
//            需要手动个Vo设置的是：eid 、exportProductId
            exportProductVo.setEid(exportVo.getId());
            exportProductVo.setExportProductId(exportProduct.getId());
            exportVo.getProducts().add(exportProductVo);
        }
        WebClient.create("http://localhost:9090/ws/export/ep").post(exportVo);


//        报运到海关后 标记为这个报运单是 已报运但没有返回结果的状态 这个状态值是5
        export.setState(5);
        exportService.update(export);

////        获取报运的结果
//        ExportResult exportResult = WebClient.create("http://localhost:9090/ws/export/ep/" + id).get(ExportResult.class);
//        exportService.updateE(exportResult); //海关数据更新

        return "redirect:/cargo/export/list.do";
    }

    @Autowired
    private DownloadUtil downloadUtil;

    @RequestMapping(value = "/exportPdf",name = "导出报运单pdf")
    public void exportPdf(String id) throws Exception{
//        当前报运单对象  货物数据
        Export export = exportService.findById(id);

        List<ExportProduct> exportProductList =  exportProductService.findByExportId(id);

//        模板路径
        String templatePath = session.getServletContext().getRealPath("/make/pdf/export.jasper");
//        把export对象转成map
        Map<String,Object> parameters = BeanMapUtils.beanToMap(export);

        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(exportProductList);
        JasperPrint jasperPrint = JasperFillManager.fillReport(new FileInputStream(templatePath), parameters,dataSource);
//        JasperExportManager.exportReportToPdfStream(jasperPrint,new FileOutputStream("d://test4.pdf"));
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint,byteArrayOutputStream);
        downloadUtil.download(byteArrayOutputStream,response,"出货表.pdf");
    }



}
